import { createSlice, createAsyncThunk, type PayloadAction } from "@reduxjs/toolkit";
import * as API from '../api/http'
import type { noticeTS, noticetypeTS } from "./crmsTS";

type initialStateTS = {
    noticelist: Array<noticeTS>
    typelist: Array<noticetypeTS>
}

//存放数据的仓库
let initialState: initialStateTS = {
    noticelist: [],//通知公告的数据
    typelist: []
}

const todosSlice = createSlice({
    name: "todos",
    initialState,
    reducers: { //同步操作

        //获取通知公告的数据
        t_noticelist(state: initialStateTS, action: PayloadAction<Array<noticeTS>>) {
            state.noticelist = action.payload
        },
        //获取通知公告的数据
        t_typelist(state: initialStateTS, action: PayloadAction<Array<noticetypeTS>>) {
            state.typelist = action.payload
        },
        //添加通知公告的数据
        t_addnotice(state: initialStateTS, action: PayloadAction<noticeTS>) {
            state.noticelist.push(action.payload)
        },
        //编辑通知公告的数据
        t_updatanotice(state: initialStateTS, action: PayloadAction<noticeTS>) {
            let i = state.noticelist.findIndex(item => {
                return item.id == action.payload.id
            })
            state.noticelist[i] = action.payload
        },
        //删除通知公告的数据
        t_delnotice(state: initialStateTS, action: PayloadAction<number>) {
            state.noticelist = state.noticelist.filter(item => {
                return item.id !== action.payload
            })
        }

    },
});

export const actionfn = todosSlice.actions;
export default todosSlice.reducer;

//异步操作 获取通知公告数据
export let async_noticelist = createAsyncThunk('async_noticelist',
    async (_, store) => {
        //调取接口 
        let res = await API.http_noticelist()
        //同步修改异步
        store.dispatch(actionfn.t_noticelist(res))
    })

//异步操作 获取通知公告数据
export let async_typelist = createAsyncThunk('async_typelist',
    async (_, store) => {
        //调取接口 
        let res = await API.http_noticelisttype()
        //同步修改异步
        store.dispatch(actionfn.t_typelist(res))
    })

//添加数据
export let async_addnotice = createAsyncThunk('async_addnotice',
    async (obj: noticeTS, store) => {
        //调取接口
        let res = await API.http_addnotice(obj)
        //同步修改异步
        store.dispatch(actionfn.t_addnotice(res))
    })
//编辑数据
export let async_updatenotice = createAsyncThunk('async_updatenotice',
    async (obj: noticeTS, store) => {
        //调取接口
        let res = await API.updatanotice(obj)
        //同步修改异步
        store.dispatch(actionfn.t_updatanotice(res))
    })
//删除数据
export let async_delnotice = createAsyncThunk('async_delnotice',
    async (id: number, store) => {
        //调取接口
        await API.delnotice(id)
        //同步
        store.dispatch(actionfn.t_delnotice(id))
    })